import { RefObject, useEffect } from "react";

/**
 * 监听元素触发点击元素外的事件
 * @param wrapper 监听元素 ref
 * @param fn 执行回调
 */
function useClickOutside(
  ref: RefObject<HTMLElement | undefined>,
  fn: () => void
) {
  //监听点击当前卡片外侧操作
  useEffect(() => {
    const handler =  (e: MouseEvent)=> {
      e.preventDefault();
      if (!ref.current || ref.current.contains(e.target as HTMLElement)) {
        return;
      }
      fn();
    };
    window.addEventListener("click", handler);

    return () => {
      window.removeEventListener("click", handler);
    };
  }, [ref,fn]);
}

export default useClickOutside;
